package com.example.octopus.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.octopus.constant.SystemConstant;
import com.example.octopus.entity.WxUserInfo;
import com.example.octopus.entity.returnMessage.SelectReturnMessage;
import com.example.octopus.entity.returnMessage.UpdateReturnMessage;
import com.example.octopus.properties.WeixinProperties;
import com.example.octopus.service.DataBaseService;
import com.example.octopus.utils.HttpClientUtil;
import com.example.octopus.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/api/login")
public class UserController {
    @Autowired
    DataBaseService impact;
    @Autowired
    WxUserInfo wxUserInfo;
    @Autowired
    private WeixinProperties weixinProperties;
    @Autowired
    private HttpClientUtil httpClientUtil;
    @RequestMapping("/login")
    public Map<String,Object> login(@RequestBody JSONObject code1){
        Object code =code1.get("code");//处理前端得到的code
        System.out.println("code是"+code);
        //System.out.println(weixinProperties.getAppid());
        //得到openid
        String jscode2sessionUrl=weixinProperties.getJscode2sessionUrl()+"?appid="+weixinProperties.getAppid()+"&secret="+weixinProperties.getSecret()+"&js_code="+code+"&grant_type=authorization_code";
        //System.out.println(jscode2sessionUrl);
        String result = httpClientUtil.sendHttpGet(jscode2sessionUrl);
        //System.out.println(result);
        JSONObject jsonObject= JSON.parseObject(result);
        String openid = jsonObject.get("openid").toString();
        //String sessionkey = jsonObject.get("session_key").toString();
        System.out.println("openid是"+openid);
        /*
        将前端传来的用户信息存储到数据库
        */
        Map<String, Object> condition=new HashMap<>();
        condition.put("_id",openid);
        SelectReturnMessage dbinfo=impact.select("user",weixinProperties.getEnv(), condition,100,0);
        String name;
        String avatar;
        if(!dbinfo.getData().isEmpty()){
            Map<String,Object> usermap =new HashMap<>();
            String Info=dbinfo.getData().get(0);
            System.out.println(Info);
            JSONObject infoobj=JSONObject.parseObject(Info);
            name=infoobj.get("username").toString();
            avatar=infoobj.get("avatar").toString();
            System.out.println(name);
            List<Object> userinfolist=new ArrayList<>();
            usermap.put("openid",openid);//openid
            usermap.put("username",name);//用户名
            usermap.put("_id",openid);//id和openid同名
            usermap.put("avatar",avatar);//用户头像
            userinfolist.add(usermap);

        }
        //System.out.println(data);
        else {
            //
            Map<String, Object> usermap = new HashMap<>();
            name = wxUserInfo.getUsername();
            avatar = wxUserInfo.getAvatar();
            List<Object> userinfolist = new ArrayList<>();
            usermap.put("openid", openid);//openid
            usermap.put("username", name);//用户名
            usermap.put("_id", openid);//id和openid同名
            usermap.put("avatar", avatar);//用户头像
            userinfolist.add(usermap);
            //插入数据库
            impact.insert("user", weixinProperties.getEnv(), userinfolist);
            System.out.println("用户插入成功");
        }
        // 利用jwt生成token返回到前端*/
        String token = JwtUtils.createJWT(openid, wxUserInfo.getUsername(), SystemConstant.JWT_TTL);
        System.out.println("token是"+token);
        Map<String,Object> resultMap=new HashMap<>();
        //返回给前端的数据*/
        if(openid!=null&&token!=null&&code!=null){
            resultMap.put("status",200);
            resultMap.put("token",token);
            resultMap.put("openid",openid);
            resultMap.put("nickName",name);
            resultMap.put("avatarUrl",avatar);
        }
        else{
            resultMap.put("status",500);
        }
        return resultMap;
    }
    //
    //获取前端的用户信息
    //
    @RequestMapping("/user")
    public Map<String,Object> putinfo(@RequestBody JSONObject userInfo){
        Map<String,Object> usermap=new HashMap<>();
        Map<String,Object> userinfomap=new HashMap<>();
        JSONObject userinfo1=userInfo.getJSONObject("userinfo");
        String nickName=userinfo1.get("nickName").toString();
        String avatarUrl=userinfo1.get("avatarUrl").toString();
        wxUserInfo.setAvatar(avatarUrl);
        wxUserInfo.setUsername(nickName);
        Object openidobj=userInfo.get("openid");
        if(openidobj!=null) {
            String openid=openidobj.toString();
            String name=wxUserInfo.getUsername();
            String avatar=wxUserInfo.getAvatar();
            Map<String,Object> usermap2 =new HashMap<>();
            usermap2.put("username",name);//用户名
            usermap2.put("avatar",avatar);//用户头像
            UpdateReturnMessage response= impact.update("user",weixinProperties.getEnv(),openid,usermap2);
            System.out.println(response);
            userinfomap.put("name",wxUserInfo.getUsername());
            userinfomap.put("avatar",wxUserInfo.getAvatar());
            usermap.put("userinfo",userinfomap);
        }
       /* userinfomap.put("name",wxUserInfo.getUsername());
        userinfomap.put("avatar",wxUserInfo.getAvatar());*/
        usermap.put("status",200);
        //usermap.put("userinfo",userinfomap);
        return usermap;
    }
    @RequestMapping("/vertify")
    public Map<String,Object> vertifyinfo(@RequestBody JSONObject Token){
        Map<String,Object> usermap=new HashMap<>();
        String token=Token.get("token").toString();
        Claims claims = JwtUtils.validateJWT(token).getClaims();
        if(claims!=null){
            usermap.put("status",200);
            usermap.put("valid",true);
        }else{
            usermap.put("status",500);
        }
        return usermap;
    }

}
